package tn.bergaoui.openwebapp.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import tn.bergaoui.openwebapp.beans.BaseBean;


public abstract class GenericJpaDao<T extends BaseBean> implements IGenericDao<T> {
	@PersistenceContext
	protected EntityManager entityManager = EMF.get().createEntityManager();

	private Class<T> entityBeanType;

	public GenericJpaDao(Class<T> entityBeanType) {
		super();
		this.entityBeanType = entityBeanType;
	}

	@Override
	public void remove(T entity) {
		entityManager.remove(entity);

	}

	@Override
	public T save(T entity) {
		return entityManager.merge(entity);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> select() {
		return entityManager.createQuery(
				"select e from " + entityBeanType.getName() + " e")
				.getResultList();
	}

	@Override
	public T selectById(Long id) {
		return entityManager.find(entityBeanType, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> search(Object... params) {
		
		final Query query = entityManager.createNativeQuery("search", entityBeanType);
		int i=1;
		for(Object param : params){
			query.setParameter(i, param);
			i++;
		}
		return query.getResultList();
	}

	public EntityManager getEntityManager() {
		return entityManager;
	}

	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}
	
	
}
